﻿package com.webdesign.service.impl;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webdesign.dao.jdbc.TbUserhomeworkSQL;
import com.webdesign.dao.mapper.TbHomeworkMapper;
import com.webdesign.dao.mapper.TbTermMapper;
import com.webdesign.dao.mapper.TbUserMapper;
import com.webdesign.dao.mapper.TbUserhomeworkMapper;
import com.webdesign.dto.CountDTO;
import com.webdesign.dto.GradeInfoDTO;
import com.webdesign.dto.TermSubmitInfoDTO;
import com.webdesign.dto.TitleSubmitInfoDTO;
import com.webdesign.dto.UserHomeworkDTO;
import com.webdesign.dto.UserhomeworkInfoDTO;
import com.webdesign.entity.TbHomework;
import com.webdesign.entity.TbHomeworkExample;
import com.webdesign.entity.TbHomeworkExample.Criterion;
import com.webdesign.entity.TbTerm;
import com.webdesign.entity.TbUser;
import com.webdesign.entity.TbUserExample;
import com.webdesign.entity.TbUserhomework;
import com.webdesign.entity.TbUserhomeworkExample;
import com.webdesign.service.ITbUserhomeworkService;
import com.webdesign.util.OuputExcelUtil;

@Service("TbUserhomeworkService")
public class TbUserhomeworkService implements ITbUserhomeworkService {

	@Autowired
	private TbUserMapper tbUserMapper;

	@Autowired
	private TbUserhomeworkMapper tbUserhomeworkMapper;

	@Autowired
	private TbHomeworkMapper tbHomeworkMapper;

	@Autowired
	private TbTermMapper tbTermMapper;
	
	/*
	 * (clover)根据作业编号，返回该作业已完成和未完成学生信息，outputGrade
	 */
	public List<GradeInfoDTO> find(String homeworkid,String title, String termid,String teacherid){
		List<GradeInfoDTO> gradeInfoDTOList = new ArrayList<GradeInfoDTO>();
		
		//根据termid返回该学年的所有学生信息
		TbUserhomeworkExample tbUserhomeworkExample = new TbUserhomeworkExample();
		TbUserExample tbUserExample = new TbUserExample();
		tbUserExample.createCriteria().andTermidEqualTo(termid).andTeacheridEqualTo(teacherid);
		List<TbUser> tbUserList = tbUserMapper.selectByExample(tbUserExample);
		String userid;
		//循环每一个学生，逐一判断是否完成
		for(TbUser tbUser : tbUserList){
			GradeInfoDTO dto = new GradeInfoDTO();
			userid = tbUser.getUserid();
			tbUserhomeworkExample.clear();
			tbUserhomeworkExample.createCriteria().andUseridEqualTo(userid).andHomeworkidEqualTo(homeworkid);
			
			List<TbUserhomework> tbUserhomeworkList = tbUserhomeworkMapper.selectByExample(tbUserhomeworkExample);
			//如果未取到信息，说明未完成作业
			if(tbUserhomeworkList.size()==0){
				dto.setUserid(userid);
				dto.setUsername(tbUser.getUsername());
				dto.setTitle(title);
				dto.setScore(0);
				dto.setClassify(null);
				dto.setState(Byte.parseByte("0"));
			}else{
				dto.setUserid(tbUser.getUserid());
				dto.setUsername(tbUser.getUsername());		
				dto.setTitle(title);
				dto.setScore(tbUserhomeworkList.get(0).getScore());
				dto.setState(tbUserhomeworkList.get(0).getState());
				dto.setClassify(tbUserhomeworkList.get(0).getClassify());

			}
			gradeInfoDTOList.add(dto);
		}
		return gradeInfoDTOList;
	}

	/*
	 *(clover)根据学年编号以及教师编号，返回所有作业的每个学生的完成情况，并生成excel表格
	 */
	@Override
	public Boolean outputGrade(String termid,String teacherid) {
		List<GradeInfoDTO> gradeInfoDTOList = new ArrayList<GradeInfoDTO>();
		TbHomeworkExample tbHomeworkExample = new TbHomeworkExample();
		tbHomeworkExample.createCriteria().andTermidEqualTo(termid).andTeacheridEqualTo(teacherid);
		List<TbHomework> tbHomeworkList = tbHomeworkMapper.selectByExample(tbHomeworkExample);
		String homeworkid;
		String title;
		List<GradeInfoDTO> dtos;
		for(TbHomework tbHomework : tbHomeworkList){
			homeworkid = tbHomework.getHomeworkid();
			title = tbHomework.getTitle();
			dtos = find(homeworkid,title,termid,teacherid);
			for(GradeInfoDTO dto : dtos){
				gradeInfoDTOList.add(dto);
			}
			 
		}

		TbTerm tbTerm = tbTermMapper.selectByPrimaryKey(termid);
		String name = tbTerm.getTermname();
		String name2[] = name.split("/");
		String name3 = name2[0] + "_" + name2[1];

		//调用OuputExcelUtil工具类生成excel表格
		return OuputExcelUtil.CreateExcel(name3, gradeInfoDTOList);
	}

	
		/*
	 * 根据学年编号，统计当前学年的所有作业的已完成人数和未完成人数
	 */
	@Override
	public List<TermSubmitInfoDTO> termSum(String termid,String userid) {
		List<TermSubmitInfoDTO> termSubmitInfoDTOs = new ArrayList<TermSubmitInfoDTO>();

		// 获得当前学年该老师人数
		TbUserExample tbUserExample = new TbUserExample();
		tbUserExample.createCriteria().andTermidEqualTo(termid).andTeacheridEqualTo(userid);
		int num = tbUserMapper.countByExample(tbUserExample);
		
		//根据学年编号获取所有作业
		TbHomeworkExample tbHomeworkExample = new TbHomeworkExample();
		tbHomeworkExample.createCriteria().andTermidEqualTo(termid);
		tbHomeworkExample.setOrderByClause("CreateTime desc");
		List<TbHomework> tbHomeworks = tbHomeworkMapper.selectByExample(tbHomeworkExample);
		
		TbUserhomeworkExample tbUserhomeworkExample = new TbUserhomeworkExample();
		TermSubmitInfoDTO termSubmitInfoDTO;
		for(TbHomework tbHomework :tbHomeworks){
			tbUserhomeworkExample.clear();
			tbUserhomeworkExample.createCriteria().andHomeworkidEqualTo(tbHomework.getHomeworkid());
			
			termSubmitInfoDTO = new TermSubmitInfoDTO();
			int finish = tbUserhomeworkMapper.countByExample(tbUserhomeworkExample);
			termSubmitInfoDTO.setHomeworkid(tbHomework.getHomeworkid());
			termSubmitInfoDTO.setTitle(tbHomework.getTitle());
			termSubmitInfoDTO.setEndtime(tbHomework.getEndtime());
			termSubmitInfoDTO.setFinishnum(finish);
			termSubmitInfoDTO.setUnfinishnum(num - finish);
			
			termSubmitInfoDTOs.add(termSubmitInfoDTO);
		}
		return termSubmitInfoDTOs;

	}


	/*
	 *按题目统计时返回的是该题目下面每个学生的完成情况
	 */
	@Override
	public List<TitleSubmitInfoDTO> titleSum(String homeworkid, String termid,String teacherid) {
		List<TitleSubmitInfoDTO> titleSubmitList = new ArrayList<TitleSubmitInfoDTO>();

		TbUserExample tbUserExample = new TbUserExample();
		tbUserExample.createCriteria().andTermidEqualTo(termid).andTeacheridEqualTo(teacherid);
		List<TbUser> tbUserList = tbUserMapper.selectByExample(tbUserExample);
		for (TbUser tbUser : tbUserList) {
			TbUserhomeworkExample tbUserhomeworkExample = new TbUserhomeworkExample();
			tbUserhomeworkExample.createCriteria().andUseridEqualTo(tbUser.getUserid()).andHomeworkidEqualTo(homeworkid);
			List<TbUserhomework> tbUserhomeworkList = tbUserhomeworkMapper.selectByExample(tbUserhomeworkExample);
			TitleSubmitInfoDTO titleSubmit = new TitleSubmitInfoDTO();
			if (tbUserhomeworkList.size() == 0) {
				titleSubmit.setUserid(tbUser.getUserid());
				titleSubmit.setUsername(tbUser.getUsername());
				titleSubmit.setState(Byte.parseByte("0"));
			} else {
				titleSubmit.setUserid(tbUser.getUserid());
				titleSubmit.setUsername(tbUser.getUsername());
				titleSubmit.setScore(tbUserhomeworkList.get(0).getScore());
				titleSubmit.setState(tbUserhomeworkList.get(0).getState());
			}
			titleSubmitList.add(titleSubmit);
		}

		return titleSubmitList;
	}
		
	/*
	 * 根据homeworkid返回某次作业已经完成的学生的作业详情
	 */
		@Override
	public List<UserHomeworkDTO> showSubmit(String homeworkid) {
		TbHomework tbHomework = tbHomeworkMapper.selectByPrimaryKey(homeworkid);
		
		TbUserhomeworkExample tbUserhomeworkExample = new TbUserhomeworkExample();
		tbUserhomeworkExample.createCriteria().andHomeworkidEqualTo(homeworkid);
		List<TbUserhomework> tbUserhomeworkList = tbUserhomeworkMapper
				.selectByExample(tbUserhomeworkExample);

		List<UserHomeworkDTO> userhomeworkDTOs = new ArrayList<UserHomeworkDTO>();
		for (TbUserhomework tbUserhomework : tbUserhomeworkList) {
			UserHomeworkDTO userHomeworkDTO = new UserHomeworkDTO();

			TbUser tbUser = tbUserMapper.selectByPrimaryKey(tbUserhomework
					.getUserid());

			userHomeworkDTO.setUserhomeworkid(tbUserhomework.getUserhomeworkid());
			userHomeworkDTO.setHomeworkid(homeworkid);
			userHomeworkDTO.setUserid(tbUserhomework.getUserid());
			userHomeworkDTO.setUsername(tbUser.getUsername());
			userHomeworkDTO.setAddress(tbUserhomework.getAddress());
			userHomeworkDTO.setScore(tbUserhomework.getScore());
			userHomeworkDTO.setGraded(tbHomework.getGraded());
			
			userhomeworkDTOs.add(userHomeworkDTO);
		}
		return userhomeworkDTOs;

	}

	/*
	 * 按课题号返回未完成的学生的信息
	 */
	@Override
	public List<TbUser> showUnsubmit(String homeworkid, String termid,String userid) {
		TbUserhomeworkExample tbUserhomeworkExample = new TbUserhomeworkExample();
		tbUserhomeworkExample.createCriteria().andHomeworkidEqualTo(homeworkid);
		List<TbUserhomework> tbUserhomeworkList = tbUserhomeworkMapper
				.selectByExample(tbUserhomeworkExample);

		List<String> submitUser = new ArrayList<String>();
		for (TbUserhomework tbUserhomework : tbUserhomeworkList) {
			submitUser.add(tbUserhomework.getUserid());
		}

		TbUserExample tbUserExample = new TbUserExample();
		if (tbUserhomeworkList.size() > 0) {
			
			tbUserExample.createCriteria().andTermidEqualTo(termid).andTeacheridEqualTo(userid).andUseridNotIn(submitUser);
		
		}else{
			tbUserExample.createCriteria().andTermidEqualTo(termid).andTeacheridEqualTo(userid);
		}
		List<TbUser> tbUserList = tbUserMapper.selectByExample(tbUserExample);
		return tbUserList;

	}


	/*
	 * 学生查看所有作业的状态
	 *
	 */
	@Override
	public List<UserhomeworkInfoDTO> homeworkState(String userid){	
		/*
		 * userid,学号
		 * homeworkid,作业号
		 */
		String homeworkid = null;		
		List<UserhomeworkInfoDTO> userhomeworkList = new ArrayList<UserhomeworkInfoDTO>();
		List<TbUserhomework> tbUserhomeworkList;		
		TbUser tbUser = tbUserMapper.selectByPrimaryKey(userid);
		//termid,学期号
		String termid = tbUser.getTermid();		
		TbHomeworkExample tbHomeworkExample = new TbHomeworkExample();	
		//取得TbHomework表中该学期所有的记录
		tbHomeworkExample.createCriteria().andTermidEqualTo(termid).getAllCriteria();
		//根据作业号降序排列
		tbHomeworkExample.setOrderByClause("HomeworkID desc");
		List<TbHomework> tbHomeworkList = tbHomeworkMapper.selectByExample(tbHomeworkExample);
		//对从TbHomework表中取出的每一条记录进行判断
		for(TbHomework tbHomework : tbHomeworkList){
			homeworkid = tbHomework.getHomeworkid();
			TbUserhomeworkExample tbUserhomeworkExample = new TbUserhomeworkExample();
			tbUserhomeworkExample.createCriteria().andHomeworkidEqualTo(homeworkid).andUseridEqualTo(userid);
			//查询时，如果有主键。可以直接使用Mapper的selectByPrimaryKey，如果不是主键，则利用Example
			tbUserhomeworkList = tbUserhomeworkMapper.selectByExample(tbUserhomeworkExample);
			//根据作业号、学号从tbHomeworkList中选择记录，如果记录不为空，说明已交该作业
			if(!(tbUserhomeworkList.isEmpty())){
					TbUserhomework tbUserhomework = tbUserhomeworkList.get(0);
					UserhomeworkInfoDTO userhomework1 = new UserhomeworkInfoDTO();
					Date submittime = tbUserhomework.getSubmittime();
					//改变提交时间的格式
					SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
					String dateString = formatter.format(submittime);  		
					userhomework1.setUserhomeworkid(tbUserhomework.getUserhomeworkid());
					userhomework1.setUserid(tbUserhomework.getUserid());
					userhomework1.setAddress(tbUserhomework.getAddress());
					userhomework1.setSubmittime(dateString);
					userhomework1.setHomeworkid(tbUserhomework.getHomeworkid());						
					userhomework1.setTitle(tbHomework.getTitle());						
					userhomework1.setScore(tbUserhomework.getScore());
					userhomework1.setState(tbUserhomework.getState());
					userhomeworkList.add(userhomework1);				
			}	
			
			//根据作业号、学号从tbHomeworkList中选择记录，如果记录为空，说明未交该作业
			else if(tbUserhomeworkList.isEmpty()){	
				//state，学生作业提交状态，0表示未交，1表示已交，2表示迟交
				Byte state = 0;
				UserhomeworkInfoDTO userhomework2 = new UserhomeworkInfoDTO();
				userhomework2.setHomeworkid(homeworkid);
				userhomework2.setAddress("#");
				userhomework2.setTitle(tbHomework.getTitle());
				userhomework2.setScore(0);
				userhomework2.setState(state);
				userhomeworkList.add(userhomework2);
			}	
		}
		return userhomeworkList;
	}
	
	
	/*
	 * 学生提交作业
	 *
	 */
	@Override
	public  Boolean submitHomework(String homeworkid,String userid){
		Byte state = 0;
		Integer score = 0;
		Date submittime = new Date();
		TbUser tbUser = tbUserMapper.selectByPrimaryKey(userid);
		String termid = tbUser.getTermid();
		String id[] = homeworkid.split("_");
		String address = "http://localhost:8080/WebDesign/homework/homework"+ id[1] + "/" + userid + "_" + id[1] + "/index.html";
		String userhomeworkid;
		TbHomework tbHomework = tbHomeworkMapper.selectByPrimaryKey(homeworkid);
		Date endtime = tbHomework.getEndtime();
		if(submittime.before(endtime)){
			//迟交
			state = 1;
		}
		else{
			//按时上交
			state = 2;
		}
		List<TbUserhomework> tbUserhomeworkList;
		TbUserhomeworkExample tbUserhomeworkExample = new TbUserhomeworkExample();
		tbUserhomeworkExample.createCriteria().andHomeworkidEqualTo(homeworkid).andUseridEqualTo(userid);
		tbUserhomeworkList = tbUserhomeworkMapper.selectByExample(tbUserhomeworkExample);
		//初次提交作业
		if(tbUserhomeworkList.isEmpty()){
			TbUserhomeworkSQL tbUserhomeworkSQL = new TbUserhomeworkSQL();
			Integer maxuserhomeworkid = Integer.parseInt(tbUserhomeworkSQL.getMaxUserhomeworkid());
			if(maxuserhomeworkid == null){
				userhomeworkid = termid + "_" + "1"; 
			}else{
				//用下划线进行分割
				userhomeworkid = termid +"_"+ String.valueOf(maxuserhomeworkid + 1 );
			}
			//评分方式是默认打分
			if(tbHomework.getGraded() == 0){
				score = 60;
			}
			TbUserhomework tbUserhomework = new TbUserhomework();
			tbUserhomework.setUserhomeworkid(userhomeworkid);
			tbUserhomework.setUserid(userid);
			tbUserhomework.setHomeworkid(homeworkid);
			tbUserhomework.setSubmittime(submittime);
			tbUserhomework.setAddress(address);
			tbUserhomework.setScore(score);
			tbUserhomework.setState(state);
			//对数据库中表的操作，都由Mapper来完成
			//将该条记录插入到表中
			if(tbUserhomeworkMapper.insertSelective(tbUserhomework)==1){
				return true;
			}else{
				return false;
			}
		}
		//重复提交作业，覆盖前一次
		else{
			for(TbUserhomework tbUsrh:tbUserhomeworkList){
				//评分方式是默认打分
				if(tbHomework.getGraded() == 0){
					score = 60;
				}
				userhomeworkid = tbUsrh.getUserhomeworkid();
				tbUsrh.setUserhomeworkid(userhomeworkid);
				tbUsrh.setUserid(userid);
				tbUsrh.setHomeworkid(homeworkid);
				tbUsrh.setSubmittime(submittime);
				tbUsrh.setAddress(address);
				tbUsrh.setScore(score);
				tbUsrh.setState(state);
				//更新数据库表该条记录
				if(tbUserhomeworkMapper.updateByPrimaryKeySelective(tbUsrh)==1){
					return true;
				}else{
					return false;
				}
			}
		}
		return true;
	}

	
	/*
	 * （12.14 clover）教师对作业进行评分
	 */
	@Override
	public Boolean grade(String userhomeworkid, String score) {
		TbUserhomework tbUserhomework = tbUserhomeworkMapper.selectByPrimaryKey(userhomeworkid);
		tbUserhomework.setScore(Integer.parseInt(score));
		if(tbUserhomeworkMapper.updateByPrimaryKey(tbUserhomework) == 1){
			return true;
		}else{
			return false;
		}
		
	}

	/*
	 * (12.15 clover)根据userhomeworkid[]返回对应的作业信息
	 */
	@Override
	public List<UserHomeworkDTO> returnUserhomework(String[] userhomeworkid) {
		TbUserhomework tbUserhomework;
		UserHomeworkDTO userhomeworkDTO;
		List<UserHomeworkDTO> userhomeworkDTOList = new ArrayList<UserHomeworkDTO>(); 
		for(int i=userhomeworkid.length-1 ; i>=0 ; i--){
			tbUserhomework = tbUserhomeworkMapper.selectByPrimaryKey(userhomeworkid[i]);
			userhomeworkDTO = new UserHomeworkDTO();
			
			userhomeworkDTO.setHomeworkid(tbUserhomework.getHomeworkid());
			userhomeworkDTO.setUserhomeworkid(tbUserhomework.getUserhomeworkid());
			TbUser tbUser = tbUserMapper.selectByPrimaryKey(tbUserhomework.getUserid());
			userhomeworkDTO.setUsername(tbUser.getUsername());
			userhomeworkDTO.setUserid(tbUserhomework.getUserid());
			userhomeworkDTO.setAddress(tbUserhomework.getAddress());
			userhomeworkDTO.setScore(tbUserhomework.getScore());
			userhomeworkDTO.setAddress(tbUserhomework.getAddress());
			
			userhomeworkDTOList.add(userhomeworkDTO);
		}
		return userhomeworkDTOList;
	}

	/*
	 *(12.16 clover)根据userhomeworkid返回homeworkid
	 */
	@Override
	public String returnHomeworkid(String userhomeworkid) {
		TbUserhomework tbUserhomework = tbUserhomeworkMapper.selectByPrimaryKey(userhomeworkid);
		return tbUserhomework.getHomeworkid();
	}
	
}

